<?php
// +----------------------------------------------------------------------
// | najing 接收测试
// +----------------------------------------------------------------------
// | Author: huangzhen
// +----------------------------------------------------------------------

namespace app\cardeadmin\controller;

use app\common\controller\AdminController;
use app\common\model\ApiAcceptOy;
use app\common\model\ErrorOy;
use app\common\model\FundCheckOy;
use app\common\model\FundCheckOyReturn;
use app\common\model\ManageLog;
use app\common\model\UserOySet;
use think\facade\Db;
use think\facade\View;


/**
 *
 * @package app\admin\controller
 */
class Usdt extends AdminController
{

    public function index()
    {
        try {

        } catch (\Exception $e) {
            dd($e->getMessage());
        }
        echo '11111';
    }

    public function oyTrans()
    {
        if($this->request->isAjax()){
            $limit      = trim(input('post.limit' , 50));
            $user_key   = trim(input('post.to_user'));
            $search_type   = trim(input('post.type'));
            $USDT_CONTRACT ="TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t";
            $API_URL       = "https://api.trongrid.io/v1/accounts";
            if(empty($user_key)){
                $user_key = getSetting('oy_fund_user');
            }
            $header         = [
                'Content-Type: application/json'
            ];

            $url = $API_URL . "/{$user_key}/transactions/trc20?limit={$limit}&only_to=true&contract_address={$USDT_CONTRACT}";

            $curl_array = [
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 10,
                CURLOPT_USERAGENT => "Mozilla/5.0 (Tronscan PHP Listener)",
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'GET',
                CURLOPT_HTTPHEADER => $header,
                CURLOPT_SSL_VERIFYPEER=>false //不检查 ssl
            ];
            $curl = curl_init();
            curl_setopt_array($curl, $curl_array);
            $response = curl_exec($curl);
            $list = [];
            $SEEN_TXIDS= [];
            if (curl_errno($curl)) {
                $list[] = [
                    'transaction_id' => curl_error($curl)
                ];
            }else{
                if(!empty($response)){
                    $data = json_decode($response, true);

                    $transfers = isset($data["data"]) ? $data["data"] : [];
                    if (!empty($transfers)) {
                        foreach ($transfers as $tx) {
                            $txid = $tx["transaction_id"];
                            $from = $tx["from"] ?? "";
                            $to = $tx["to"] ?? "";
                            $amount = floatval($tx["value"]) / 1e6;
                            $ts = intval($tx["block_timestamp"]) / 1000;
                            $time_str = date("Y-m-d H:i:s", $ts);
                            $type = $tx["type"];
                            $new_tx = [
                                "txid" => $txid,
                                "time" => $time_str,
                                "amount" => $amount,
                                "from" => $from,
                                "to" => $to,
                                "type" => $type,
                            ];
                            if(!empty($search_type)){
                                if($type == $search_type){
                                    $SEEN_TXIDS[] = $new_tx;
                                }
                            }else{
                                $SEEN_TXIDS[] = $new_tx;
                            }
                        }
                    }
                }
            }
            curl_close($curl);
            $result = [
                'code'  => 0,
                'msg'   => lang('get info success'),
                'data'  => $SEEN_TXIDS,
                'count' => count($SEEN_TXIDS),
            ];
            return $result;
        }
        return View::fetch();
    }

    public function usdtFund()
    {
        if($this->request->isPost()) {
            $data = input('param.');
            $cdModel = new FundCheckOy();
            return $cdModel->tableDataAdmin($data);
        }
        return View::fetch();
    }

    public function usdtReturn()
    {
        if($this->request->isPost()) {
            $data = input('param.');
            $cdModel = new FundCheckOyReturn();
            return $cdModel->tableDataAdmin($data);
        }
        return View::fetch();
    }

    public function usdtAccept()
    {
        if($this->request->isPost()) {
            $data = input('param.');
            $cdModel = new ApiAcceptOy();
            return $cdModel->tableDataAdmin($data);
        }
        return View::fetch();
    }

    public function usdtError()
    {
        if($this->request->isPost()) {
            $data = input('param.');
            $cdModel = new ErrorOy();
            return $cdModel->tableDataAdmin($data);
        }
        return View::fetch();
    }

    public function usdtUser()
    {
        if($this->request->isPost()) {
            $data = input('param.');
            $cdModel = new UserOySet();
            return $cdModel->tableDataAdmin($data);
        }
        return View::fetch();
    }
    public function usdtActionError()
    {
        $data = input('param.');
        $remark       = $data['remark'];
        $return_id    = $data['return_id'];
        $re           = Db::name('fund_check_oy_return')
            ->where(['id'=>$return_id])
            ->update([
                'is_ok'        => 2,
                'remark'       => $remark,
                'manage_id'     => $this->manage_id,
                'utime'        => getUtcTime(false)
            ]);
        if($re){
            return $this->scs('confirm success');
        }else{
            return $this->err('confirm error');
        }
    }
    public function usdtAction()
    {
        if($this->request->isPost()) {
            //header("HTTP/1.1 402"); exit;
            $data = input('param.');
            $ok_history   = $data['ok_history'];
            $remark       = $data['remark'];
            $return_id    = $data['return_id'];

            $utime    = getUtcTime(false);
            $time     = strtotime($utime);
            $msg      = '';
            $blog = false;
            if(!empty($ok_history)){
                $return_list = Db::name('fund_check_oy_return')->where(['id'=>$return_id])->find();
                $user_id =$return_list['user_id'];
                $amount     = $return_list['amount'];
                $return_time = $return_list['ctime'];
                $out_trade_no = $return_list['out_trade_no'];

                $user_list  = Db::name('user')->where(['id'=>$user_id])->find();
                $username   = $user_list['username'];
                $user_balance   = $user_list['balance'];
                //新订单号
                $trade_no_new  = 'OY' . date('YmdHis') . getRandNumber(0,9,6);
                //手续费
                $oy_rate           = Db::name('user_oy_set')
                    ->where(['user_id' => $user_id])->value('rate');
                //pay_user
                $api_accept_list = Db::name('api_accept_oy')->where(['id'=>$ok_history])->find();
                $pay_user = $api_accept_list['to'];
                $hash     = $api_accept_list['txid'];
                //减去手续费部分
                $money  = intval($amount);
                $money  = $money - intval($money*$oy_rate);

                Db::startTrans();
                try {
                    Db::name('fund_check_oy_return')->where(['id'=>$return_id])->update([
                        'is_ok'        => 1,
                        'remark'       => $remark,
                        'trade_no_new' => $trade_no_new,
                        'utime'     => $utime,
                        'manage_id' => $this->manage_id
                    ]);
                    Db::name('api_accept_oy')->where(['id'=>$ok_history])->update([
                        'user_id' => $user_id,
                        'out_trade_no' => $trade_no_new,
                        'remark'   => $remark,
                        'is_action' => 1,
                        'utime'     => $utime
                    ]);

                    $result_balance = $user_balance + $money;
                    //记录钱包日志
                    Db::name('user_cash_log')->save([
                        'user_id'       => $user_id,
                        'type'          => 0, //1=debit
                        'action_type'   => 1, //3=消费
                        'amount'        => $money,
                        'balance'       => $result_balance, //如果是进行修复的话，这里的余额要重新计算
                        'desc'          => "USDT充值",
                        'remark'        => $trade_no_new,
                        'ctime'         => $time
                    ]);
                    //记录到总充值列表中
                    $check_num  = 'U' . getRandNumber();
                    Db::name('fund_check')->save([
                        'user_id'       => $user_id,
                        'check_num'     => $check_num,
                        'amount'        => $money,
                        'balance'       => $result_balance,
                        'ctime'         => $time,
                        'utime'         => $time,
                        'check_status'  => 1,
                        'pay_type'      => 6,  //6=usdt付款
                        'trn'           => $trade_no_new,
                        'remark'        => "old订单:{$out_trade_no}",
                        'desc'          => "USDT充值",
                        'hash'          => $hash
                    ]);
                    //新建usdt充值列表
                    Db::name('fund_check_oy')
                        ->save([
                            'user_id'       => $user_id,
                            'out_trade_no'  => $trade_no_new,
                            'amount'        => $money, //实冲金额
                            'amount_real'   => $amount, //充值金额
                            'ctime'         => $return_time,
                            'utime'         => $utime,
                            'pay_user'      => $pay_user,
                            'status_check'  => 1,
                            'status_used'   => 1,
                            'msg'           => "old订单:{$out_trade_no}"
                        ]);
                    //充值成功后更新用户余额
                    Db::name('user')->where(['id'=>$user_id])->update(['balance'=>$result_balance]);
                    //old工单状态更新为 5=工单处理
                    Db::name('fund_check_oy')->where(['out_trade_no'=>$out_trade_no])
                        ->update(['status_check'=>5]);
                    $blog = true;
                    Db::commit();
                } catch (\Exception $e) {
                    $error_msg  = $e->getMessage();
                    Db::name('error_oy')->save([
                        'user_id'       => $user_id,
                        'error_msg'     => $error_msg,
                        'detail'        => json_encode([
                            'return_id' => $return_id,
                            'username'  => $username,
                        ]),
                        'time'          => $utime
                    ]);
                    $msg = '充值失败';
                    Db::rollback();
                }
            }else{
                $msg = '请选择对应爬虫日志';
                $blog = false;
            }


            if($blog){
                return $this->scs('confirm success');
            }else{
                return $this->err($msg);
            }
        }
        $return_id = input('get.id');
        $list      = Db::name('fund_check_oy_return')->where(['id'=>$return_id])->find();
        $out_trade_no = $list['out_trade_no'];
        $fund_oy_list = Db::name('fund_check_oy')->where(['out_trade_no'=>$out_trade_no])->find();
        $username  = Db::name('user')->where(['id'=>$list['user_id']])->value('username');
        $list_array= Db::name('api_accept_oy')
            ->where([
                'amount'=>$list['amount'],
                'is_action' => 0,
                'type' => 'Transfer',
            ])
            ->select()->toArray();
        $is_show    = true;
        $error_msg  = '';
        if(empty($list_array)){
            $is_show = false;
            $error_msg = '系统未匹配到您的付款记录,可能因金额填写有误或尚未到账,请确认后重试.';
            Db::name('fund_check_oy_return')->where(['id'=>$return_id])->update([
                'is_ok'        => 2,
                'remark'       => $error_msg,
                'utime'         => getUtcTime(false)
                ]);
        }
        View::assign([
            'return_id'      => $return_id,
            'username'      =>  $username,
            'list'          =>  $list,
            'list_array'    =>  $list_array,
            'fund_oy_list'  =>  $fund_oy_list,
            'is_show'       =>  $is_show,
            'error_msg'     =>  $error_msg
        ]);
        return View::fetch();
    }

    /*
 * 超额等处理
 */
    public function usdtActionLimit()
    {
        if($this->request->isPost()) {
            $data = input('param.');
            $ok_history_id      = $data['ok_history'];
            $usdt_fund_id    = $data['usdt_fund_id'];

            $utime    = getUtcTime(false);
            $time     = strtotime($utime);
            $msg      = '';
            $blog = false;
            if(!empty($ok_history_id)){
                $fund_list    = Db::name('fund_check_oy')->where(['id'=>$usdt_fund_id])->find();
                $user_id      = $fund_list['user_id'];
                $amount       = $fund_list['amount'];
                $out_trade_no = $fund_list['out_trade_no'];

                $user_list      = Db::name('user')->where(['id'=>$user_id])->find();
                $username       = $user_list['username'];
                $user_balance   = $user_list['balance'];

                $result_balance = getSprintf($user_balance + $amount);
                $hash           = Db::name('api_accept_oy')->where(['id'=>$ok_history_id])->value('txid');
                Db::startTrans();
                try {
                    Db::name('api_accept_oy')->where(['id'=>$ok_history_id])->update([
                        'user_id' => $user_id,
                        'out_trade_no' => $out_trade_no,
                        'remark'   => '超限额已处理',
                        'is_action' => 1,
                        'utime'     => $utime
                    ]);
                    //记录钱包日志
                    Db::name('user_cash_log')->save([
                        'user_id'       => $user_id,
                        'type'          => 0, //1=debit
                        'action_type'   => 1, //3=消费
                        'amount'        => $amount,
                        'balance'       => $result_balance, //如果是进行修复的话，这里的余额要重新计算
                        'desc'          => "USDT充值",
                        'remark'        => $out_trade_no,
                        'ctime'         => $time
                    ]);
                    //记录到总充值列表中
                    $check_num  = 'U' . getRandNumber();
                    Db::name('fund_check')->save([
                        'user_id'       => $user_id,
                        'check_num'     => $check_num,
                        'amount'        => $amount,
                        'balance'       => $result_balance,
                        'ctime'         => $time,
                        'utime'         => $time,
                        'check_status'  => 1,
                        'pay_type'      => 6,  //6=usdt付款
                        'trn'           => $out_trade_no,
                        'remark'        => "old订单:{$out_trade_no}",
                        'desc'          => "USDT充值",
                        'hash'          => $hash
                    ]);
                    Db::name('fund_check_oy')
                        ->where(['id'=>$usdt_fund_id])
                        ->update([
                            'status_check'    => 1,
                            'status_used'     => 1,
                            'utime'           => $utime,
                        ]);
                    //充值成功后更新用户余额
                    Db::name('user')->where(['id'=>$user_id])->update(['balance'=>$result_balance]);
                    $blog = true;
                    Db::commit();
                } catch (\Exception $e) {
                    $error_msg  = $e->getMessage();
                    Db::name('error_oy')->save([
                        'user_id'       => $user_id,
                        'error_msg'     => $error_msg,
                        'detail'        => json_encode([
                            'msg'       => '超额等处理失败',
                            'usdt_fund_id' => $usdt_fund_id,
                            'username'  => $username,
                        ]),
                        'time'          => $utime
                    ]);
                    $msg = '充值失败';
                    Db::rollback();
                }
            }else{
                $msg = '请选择对应爬虫日志';
            }
            if($blog){
                return $this->scs('confirm success');
            }else{
                return $this->err($msg);
            }
        }
        $usdt_fund_id   = input('get.id');
        $list      = Db::name('fund_check_oy')->where(['id'=>$usdt_fund_id ,'status_check'=>6])->find();
        $username  = Db::name('user')->where(['id'=>$list['user_id']])->value('username');
        $list_array= Db::name('api_accept_oy')
            ->where([
                'amount'=>$list['amount_real'],
                'is_action' => 0,
                'type' => 'Transfer'
            ])
            ->select()->toArray();

        View::assign([
            'usdt_fund_id'  => $usdt_fund_id,
            'username'      =>  $username,
            'list'          =>  $list,
            'list_array'    =>  $list_array,
        ]);
        return View::fetch();
    }

    public function usdtAdd()
    {
        if($this->request->isPost()) {
            //header("HTTP/1.1 402"); exit;
            $data = input('param.');
            $user       = $data['name'];
            $rate       = $data['rate'];
            $user_list  = Db::name('user')->where(['username'=>$user])->find();
            if(empty($user_list)){
                return $this->err('用户不存在.');
            }
            $user_id    = $user_list['id'];
            $oy_list    = Db::name('user_oy_set')->where(['id'=>$user_id])->find();
            if(!empty($oy_list)){
                return $this->err('用户USDT已设置.');
            }
            $create_time=getUtcTime();

            $re   = Db::name('user_oy_set')->save([
                'user_id'  => $user_id,
                'rate'  => $rate,
                'time'     => $create_time
            ]);

            if($re){
                return $this->scs('add success');
            }else{
                return $this->err('add error');
            }
        }
        return View::fetch();
    }

    /**
     * 更新全部用户汇率
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function usdtRate()
    {
        if($this->request->isPost()) {
            $data       = input('param.');
            $rate       = $data['rate'];
            $result = [
                'status' => false,
                'msg'    => '失败',
                'data'   => ''
            ];
            $parts = explode('.',(string)$rate);
            if (count($parts) > 1) {
                $decimalPlaces = strlen($parts[1]);
            } else {
                $decimalPlaces = 0;
            }
            if($decimalPlaces == 2 && $rate >0 && $rate < 1){
                $re = Db::name('user_oy_set')->where('id >=1')->update(['rate'=>$rate]);
                if ($re) {
                    $result['status'] = true;
                    $result['msg']    = '编辑成功';
                    ManageLog::saveManageLog([
                        'manage_id' => $this->manage_id ,
                        'desc'      => 'Usdt User all set Update',
                        'content'   => ['username'   => 'all' , 'rate_new' => $rate]
                    ]);
                } else {
                    $result['msg'] = '编辑失败，请重试';
                }
            }else{
                $result['msg'] = '必须大于0,小于1,并且小数点后只能两位';
            }
            return $result;
        }
        View::layout(false);
        return [
            'status'    => true,
            'datas'     => View::fetch()
        ];
    }
    public function edit()
    {
        if($this->request->isPost()) {
            $data       = input('param.');
            $oy_id      = $data['oy_id'];
            $username   = $data['username'];
            $rate       = $data['rate'];
            $result = [
                'status' => false,
                'msg'    => '失败',
                'data'   => ''
            ];
            $parts = explode('.',(string)$rate);
            if (count($parts) > 1) {
                $decimalPlaces = strlen($parts[1]);
            } else {
                $decimalPlaces = 0;
            }
            if($decimalPlaces <=2){
                $old_rate = Db::name('user_oy_set')->where(['id' => $oy_id])->value('rate');
                $re = Db::name('user_oy_set')->where(['id' => $oy_id])->update(['rate'=>$rate]);
                if ($re) {
                    $result['status'] = true;
                    $result['msg']    = '编辑成功';
                    ManageLog::saveManageLog([
                        'manage_id' => $this->manage_id ,
                        'desc'      => 'Usdt User set Update',
                        'content'   => ['username'   => $username , 'rate_old' => $old_rate ,'rate_new' => $rate]
                    ]);
                } else {
                    $result['msg'] = '编辑失败，请重试';
                }
            }else{
                $result['msg'] = '只能小数点后两位';
            }
            return $result;
        }

        $oy_id = input('get.id');
        $oy_info = Db::name('user_oy_set')->where(['id' => $oy_id])->find();
        $user_id = $oy_info['user_id'];
        $username= Db::name('user')->where(['id' => $user_id])->value('username');
        View::assign([
            'username'      => $username,
            'oy_info'       => $oy_info
        ]);
        View::layout(false);
        return [
            'status'    => true,
            'datas'     => View::fetch()
        ];
    }

    public function del()
    {
        $result = [
            'status' => false,
            'msg'    => '失败',
            'data'   => ''
        ];
        $data = input('param.');
        $id   = $data['id'];
        $oy_set_list = Db::name('user_oy_set')->where(['id'=>$id])->find();
        $user_id     = $oy_set_list['user_id'];
        $rate        = $oy_set_list['rate'];
        $username    = Db::name('user')->where(['id'=>$user_id])->value('username');
        $re          = Db::name('user_oy_set')->where(['id'=>$id])->delete();
        if ($re) {
            $result['status'] = true;
            $result['msg']    = '删除成功';
            ManageLog::saveManageLog([
                'manage_id' => $this->manage_id ,
                'desc'      => 'Usdt User set del',
                'content'   => ['username'   => $username , 'rate' => $rate]
            ]);
        } else {
            $result['msg'] = '删除失败，请重试';
        }

        return $result;
    }
}